/**
 * Create in 2012-7-27.
 */
package kit4j.tests.jdk.swing.dnd.component;

import java.awt.Component;
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.List;

import javax.swing.DropMode;
import javax.swing.JLabel;
import javax.swing.JPanel;

import kit4j.tests.jdk.swing.dnd.factory.EmptyLabelFactory;
import kit4j.view.cs.swing.dnd.ComponentMoveTransferHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 按钮面板组件。所有按钮以同样的尺寸以指定的行数和列数显示在面板上。
 * 
 * @author MiniKnife
 * 
 */
public class JButtonBox extends JPanel {

	private static final long serialVersionUID = 1L;

	private static final Logger log = LoggerFactory.getLogger(JButtonBox.class);

	private int rows;

	private int cols;

	private int lastIndex;

	private List<JLabel> emptyButtonList;

	/**
	 * 
	 */
	public JButtonBox(int rows, int cols) {
		lastIndex = 0;
		setBoxSize(rows, cols);
		initTransferHandler();
		initEmptyButtonList();
		initEmptyBox();
	}

	private void initTransferHandler() {
		ComponentMoveTransferHandler transferHanlder = new ComponentMoveTransferHandler(this);
		transferHanlder.setDropMode(DropMode.INSERT);

		setTransferHandler(transferHanlder);
	}

	private void initEmptyButtonList() {
		int count = rows * cols;
		emptyButtonList = Arrays.asList(EmptyLabelFactory.createUniqueLabel(count));
	}

	private void initEmptyBox() {
		for (JLabel lb : emptyButtonList) {
			super.add(lb);
		}
	}

	@Override
	public Component add(Component comp) {
		return add(comp, lastIndex);
	}

	@Override
	public Component add(Component comp, int index) {
		if (getComponentZOrder(comp) != -1) {
			super.remove(comp);
		}

		super.remove(index);
		super.add(comp, index);

		if (index <= lastIndex) {
			do {
				++lastIndex;
			} while (!(getComponent(lastIndex) instanceof JLabel));
		}

		log.debug("add component at {} and lastIndex = {}.", index, lastIndex);

		return comp;
	}

	@Override
	public void remove(Component comp) {
		int index = getComponentZOrder(comp);

		if (index != -1) {
			remove(index);
		}
	}

	@Override
	public void remove(int index) {
		if (index < lastIndex) {
			lastIndex = index;
		}

		super.remove(index);
		super.add(emptyButtonList.get(index), index);

		log.debug("remove component at {} and lastIndex = {}.", index, lastIndex);
	}

	public void setBoxSize(int rows, int cols) {
		this.rows = rows;
		this.cols = cols;
		setLayout(new GridLayout(rows, cols));
	}
}
